package com.ohos.ringdroid;

import com.ohos.ringdroid.slice.MainAbilitySlice;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.SystemMemoryInfo;
import ohos.aafwk.content.Intent;
import ohos.security.SystemPermission;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import static ohos.bundle.IBundleManager.PERMISSION_GRANTED;

public class MainAbility extends Ability {
    private static final int PERMISSION_REQUEST_CODE = 1;
    private static final String TAG = MainAbility.class.getSimpleName();

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(MainAbilitySlice.class.getName());
//        super.setMainRoute(MyTestAbilitySlice.class.getName());
        requestPermission();
    }

    private void requestPermission() {
        List<String> permissions;
        permissions = new LinkedList<>(
                Arrays.asList(
                        SystemPermission.WRITE_MEDIA,
                        SystemPermission.READ_MEDIA,
                        SystemPermission.WRITE_USER_STORAGE,
                        SystemPermission.READ_USER_STORAGE,
                        SystemPermission.MICROPHONE,
                        SystemPermission.MANAGE_USER_STORAGE));
        permissions.removeIf(permission ->
                verifySelfPermission(permission) == PERMISSION_GRANTED || !canRequestPermission(permission));
        if (!permissions.isEmpty()) {
            requestPermissionsFromUser(permissions.toArray(new String[0]), PERMISSION_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode != PERMISSION_REQUEST_CODE) {
            return;
        }
        for (int grantResult : grantResults) {
            if (grantResult != PERMISSION_GRANTED) {
                LogUtil.info(TAG, grantResult + " is denied , Some functions may be affected.");
            }
        }
    }
}
